﻿using Sidvall.Serialization;

namespace Sidvall.Security
{
    public class Claim
    {
        #region Public Members

        public string ClaimType { get; set; }
        public string Value { get; set; }
        public string ValueType { get; set; }

        #region Equals

        public bool Equals(Claim claim)
        {
            if (claim == null)
                return false;
            return Equals(claim.ClaimType, claim.Value);
        }
        public bool Equals(string claimType, string value)
        {
            return claimType.Equals(this.ClaimType, true, System.StringComparison.OrdinalIgnoreCase) && value.Equals(this.Value, true, System.StringComparison.OrdinalIgnoreCase);
        }

        #endregion
        #region GetObjectValue

        public T GetObjectValue<T>()
        {
            if (_ObjectValue == null)
            {
                lock (_Mutex)
                {
                    if (_ObjectValue == null)
                    {
                        var value = Sidvall.Serialization.SerializerManager.Current.Deserialize<T>(this.Value);
                        _ObjectValue = value;
                        return value;
                    }
                }
            }
            return (T)_ObjectValue;
        }

        #endregion
        #region ToString

        public override string ToString()
        {
            if (!string.IsNullOrWhiteSpace(this.ClaimType))
            {
                if (!string.IsNullOrWhiteSpace(this.Value))
                    return this.ClaimType + ": " + this.Value;
                return this.ClaimType;
            }
            return null;
        }

        #endregion

        #endregion
        #region Private Members

        private readonly object _Mutex = new object();
        private object _ObjectValue;

        #endregion
    }
}
